import { Server } from 'ws'
import MessagePublisher from "./MessageCenter";

const port = parseInt(process.env.WEBSOCKET_PORT) || 2883;

//
const socketGroupMapping = {};

function start() {
    // 创建WebSocket服务器
    const server = new Server({ port: port });

    // 当客户端连接时
    server.on('connection', (socket, request) => {

        const url = request.url;
        const deviceId = url.substring(1);
        if (!socketGroupMapping[deviceId]) {
            socketGroupMapping[deviceId] = [];
        }
        socketGroupMapping[deviceId].push(socket);

        // 接收客户端消息
        socket.on('message', (message) => {
            const msg = message.toString();
            console.log(`Received message: ${msg}`);
        });

        // 当客户端关闭连接
        socket.on('close', () => {
            console.log(`Client disconnected.`);
        });

        MessagePublisher.subscribe((msg:string) => {
            socket.send(msg);

        })

    });

    console.log(`启动Websocket服务，端口：${port}`);
}



export default {
    start
}


